//
//  ProfileViewController.m
//  Systetagram
//
//  Created by 欧杨 on 2021/1/6.
//

#import <AFNetworking.h>
#import <Masonry.h>

#import "AppDelegate.h"
#import "ProfileViewController.h"
#import "HomeCollectionViewCell.h"
#import "UICollectionViewMultiFlowLayout.h"
#import "ListViewController.h"

static NSString *homeCellReuseIdentifier = @"cell";

@interface ProfileViewController ()<UICollectionViewDataSource>

@property UIActivityIndicatorView *loading;

@end

@implementation ProfileViewController

- (instancetype)init
{
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    self = [self initWithUserID:myDelegate.userID];
    return self;
}

- (instancetype)initWithUserID:(NSNumber *)userID
{
    self = [super init];
    if (self) {
        self.operationCount = 0;
        [self setupDataWithUserID:userID];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *unselected = [[UIImage imageNamed:@"face"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImage *selected = [[UIImage imageNamed:@"face"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UITabBarItem *tabbarItem = [[UITabBarItem alloc] initWithTitle:nil image:unselected selectedImage:selected];
    self.tabBarItem = tabbarItem;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.loading = [[UIActivityIndicatorView alloc] init];
    self.loading.center = self.view.center;
    self.loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge;
    [self.loading startAnimating];
}

-(void)setupSubviews
{
    [self.loading stopAnimating];
    [self.view addSubview:self.background];
    [self.view addSubview:self.profilePic];
    [self.view addSubview:self.nickName];
    [self.view addSubview:self.follow];
    [self.view addSubview:self.followsNum];
    [self.view addSubview:self.fansNum];
    [self.view addSubview:self.likeNum];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColor.lightGrayColor;
    [self.view addSubview:line];
    [self.view addSubview:self.collectionView];
    
    [_background mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(150);
        make.top.left.right.equalTo(self.view);
    }];
    [_profilePic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(75, 75));
        make.left.equalTo(self.view).mas_offset(20);
        make.top.equalTo(_background.mas_bottom).offset(-20);
    }];
    [_nickName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_profilePic.mas_right).mas_offset(10);
        make.top.equalTo(_background.mas_bottom).mas_offset(5);
    }];
    [_followsNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.left.equalTo(_profilePic.mas_right).mas_offset(30);
        make.top.equalTo(_nickName.mas_bottom);
    }];
    [_fansNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.left.equalTo(_followsNum.mas_right).mas_offset(22);
        make.top.equalTo(_nickName.mas_bottom);
    }];
    [_likeNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.left.equalTo(_fansNum.mas_right).mas_offset(22);
        make.top.equalTo(_nickName.mas_bottom);
    }];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_followsNum.mas_bottom).mas_offset(25);
        make.height.mas_equalTo(1);
        make.left.equalTo(self.view).mas_offset(10);
        make.right.equalTo(self.view).mas_offset(-10);
    }];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line.mas_bottom).mas_offset(10);
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view).mas_offset(10);
        make.right.equalTo(self.view).mas_offset(-10);
    }];
    [_follow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_profilePic.mas_bottom).offset(15);
        make.centerX.equalTo(_profilePic);
    }];
}

- (void)setOperationCount:(NSUInteger)operationCount
{
    _operationCount = operationCount;
    if (_operationCount == 4) {
        NSLog(@"setup finished");
        [self setupSubviews];
    }
}

- (UIImageView *)background
{
    if (!_background) {
        _background = [[UIImageView alloc] init];
        _background.backgroundColor = UIColor.lightGrayColor;
        NSString *url = [NSString stringWithFormat:@"%@%@",@"http://47.107.247.52:8080/", self.user.background];
        NSURL *imageURL = [NSURL URLWithString:url];
        NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithURL:imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.background setImage:[UIImage imageWithData:data]];
                });
            }
        }];
        [task resume];
    }
    return _background;
}

- (UIImageView *)profilePic
{
    if (!_profilePic) {
        _profilePic = [[UIImageView alloc] init];
        _profilePic.backgroundColor = UIColor.lightGrayColor;
        NSString *url = [NSString stringWithFormat:@"%@%@",@"http://47.107.247.52:8080/", self.user.avatar];
        NSURL *imageURL = [NSURL URLWithString:url];
        NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithURL:imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.profilePic setImage:[UIImage imageWithData:data]];
                });
            }
        }];
        [task resume];
    }
    return _profilePic;
}

- (UILabel *)nickName
{
    if (!_nickName) {
        _nickName = [[UILabel alloc] init];
        _nickName.text = _user.username;
        _nickName.font = [_nickName.font fontWithSize:26];
    }
    return _nickName;
}

- (UIButton *)follow
{
    if (!_follow) {
        _follow = [UIButton buttonWithType:UIButtonTypeSystem];
        [_follow setTitle:@"关注" forState:UIControlStateNormal];
    }
    return _follow;
}

- (UILabel *)followsNum
{
    if (!_followsNum) {
        _followsNum = [[UILabel alloc] init];
        _followsNum.numberOfLines = 0;
        _followsNum.font = [_followsNum.font fontWithSize:26];
        //_followsNum.backgroundColor = UIColor.redColor;
        _followsNum.textAlignment = NSTextAlignmentCenter;
        _followsNum.text = [NSString stringWithFormat:@"关注\n%lu", self.followsList.count];
        _followsNum.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(followsClicked)];
        [_followsNum addGestureRecognizer:singleGesture];
    }
    return _followsNum;
}

- (UILabel *)fansNum
{
    if (!_fansNum) {
        _fansNum = [[UILabel alloc] init];
        _fansNum.numberOfLines = 0;
        _fansNum.font = [_followsNum.font fontWithSize:26];
        //_fansNum.backgroundColor = UIColor.redColor;
        _fansNum.textAlignment = NSTextAlignmentCenter;
        _fansNum.text = [NSString stringWithFormat:@"粉丝\n%lu", self.fansList.count];
        _fansNum.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(followsClicked)];
        [_fansNum addGestureRecognizer:singleGesture];
    }
    return _fansNum;
}

- (UILabel *)likeNum
{
    if (!_likeNum) {
        _likeNum = [[UILabel alloc] init];
        _likeNum.numberOfLines = 0;
        _likeNum.font = [_followsNum.font fontWithSize:26];
        //_likeNum.backgroundColor = UIColor.redColor;
        _likeNum.textAlignment = NSTextAlignmentCenter;
        _likeNum.text = [NSString stringWithFormat:@"获赞\n%lu", self.user.like.unsignedLongValue];
        _likeNum.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(followsClicked)];
        [_fansNum addGestureRecognizer:singleGesture];
    }
    return _likeNum;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewMultiFlowLayout *flowLayout = [[UICollectionViewMultiFlowLayout alloc] init];
        flowLayout.items = self.blogList;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.whiteColor;
        [_collectionView registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:homeCellReuseIdentifier];
    }
    return _collectionView;
}

- (void)setupDataWithUserID:(NSNumber *)userID
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSString *URLString = @"http://47.107.247.52:8080/user";
    NSDictionary *parameters = @{@"id":userID};
    [manager POST:URLString parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@", responseObject);
        if ([responseObject[@"ok"] boolValue]) {
            self.user = [[userModel alloc] initWithDictionary:((NSDictionary *)responseObject)[@"data"]];
            self.operationCount += 1;
        } else {
            NSLog(@"something wrong when get profile");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
    
    parameters = @{@"user_id":userID};
    URLString = @"http://47.107.247.52:8080/followlist";
    [manager POST:URLString parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@", responseObject);
        self.followsList = [NSMutableArray array];
        if ([responseObject[@"ok"] boolValue]) {
            for (NSDictionary *dic in ((NSDictionary *)responseObject)[@"data"]) {
                [self.followsList addObject:[[userModel alloc] initWithDictionary:dic]];
            }
            self.operationCount += 1;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failed");
    }];
    
    URLString = @"http://47.107.247.52:8080/befollowlist";
    [manager POST:URLString parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@", responseObject);
        self.fansList = [NSMutableArray array];
        if ([responseObject[@"ok"] boolValue]) {
            for (NSDictionary *dic in ((NSDictionary *)responseObject)[@"data"]) {
                [self.fansList addObject:[[userModel alloc] initWithDictionary:dic]];
            }
            self.operationCount += 1;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failed");
    }];
    
    URLString = @"http://47.107.247.52:8080/user/blog";
    parameters = @{@"idarr":@[userID]};
    [manager POST:URLString parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@", responseObject);
        self.blogList = [NSMutableArray array];
        if ([responseObject[@"ok"] boolValue]) {
            if ([responseObject[@"data"] isKindOfClass:[NSNull class]]) {
                
            } else
                for (NSDictionary *dic in ((NSDictionary *)responseObject)[@"data"]) {
                    [self.blogList addObject:[[blogModel alloc] initWithDictionary:dic]];
                }
            self.operationCount += 1;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failed");
    }];
}

#pragma mark - DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.blogList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:homeCellReuseIdentifier forIndexPath:indexPath];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"http://47.107.247.52:8080/", self.blogList[indexPath.item].picture];
    NSURL *imageURL = [NSURL URLWithString:url];
    NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithURL:imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage *image = [UIImage imageWithData:data];
                [cell setBackgroundView:[[UIImageView alloc] initWithImage:image]];
                [cell configureGesture];
                cell.model = self.blogList[indexPath.item];
                cell.image = image;
            });
        }
    }];
    [task resume];
    return cell;
}

#pragma mark - gesture

-(void)followsClicked
{
    NSLog(@"list clicked");
    ListViewController *VC = [[ListViewController alloc] initWithList:self.followsList];
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)fansClicked
{
    NSLog(@"list clicked");
    ListViewController *VC = [[ListViewController alloc] initWithList:self.fansList];
    [self.navigationController pushViewController:VC animated:YES];
}


@end
